import time,datetime,re,requests,pyautogui,pytest,random,shutil,yaml,inspect
from common.readfile import Yaml
from selenium import webdriver
from common.config import *
from selenium.webdriver.support.select import Select
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.action_chains import ActionChains

'''读写文件'''
def write_file(filepath,data):
    fr = open(filepath, 'a')#打开文件
    yaml.dump(data, fr)#写入数据
    fr.close()#关闭文件


'''删除非空目录'''
def shu_til(path):
    #path:目录路径
    shutil.rmtree(path)

'''产生随机数'''
def random_number(val,vaule):
    if type(vaule) == int and type(val) == int:#整数
        return random.randint(val, vaule)
    elif type(vaule) == float and type(val) == float:#浮点数
        return random.randint(val, vaule)

'''获取项目根目录'''
def rootpath():
    try:
        path = os.path.split(os.path.dirname(os.path.abspath(__file__)))[0]# 获取该工程的绝对路径
    except BaseException as  msg:
        print(msg)
    return path



'''全屏截图'''
def get_img(name):
    check_list(IMA_PATH)
    Timestamp = date("%Y-%m-%d %H_%M_%S")
    im = pyautogui.screenshot()
    # CASE_PATH = os.path.join(IMA_PATH,name+ Timestamp + ".png")  # 用例路径
    CASE_PATH = os.path.join(IMA_PATH, name)  # 用例路径
    im.save(CASE_PATH)



'''正则提取，返回列表格式'''
def reguEX(str,str1,data):
    # data ='a123b'
    p1 = re.compile(r'['+str+'](.*?)['+str1+']', re.S)#多行匹配，那么需要加上re.S和re.M标志. 加上re.S后, .将会匹配换行符，默认.不会匹配换行符.
    da = re.findall(p1, data)
    return da

'''正则提取，返回列表格式'''
def regEx(regEx,data):
    data = re.findall(regEx, data)  # regEx：正则提取表达式；data：字符串
    return data

'''判断某个字符串是否存在于列表中'''
def containslist(str,list):
    #list:列表；str:字符串
    if str in list:
        return True
    else:
        return False

'''分割字符串'''
def segmentation(str,Split):
    try:
        val = str.split(Split)
        str = val[0] #分隔符前的数据
        value = val[1]#分隔符后的数据
    except BaseException as  msg:
        print(msg)
    return str,value



'''文件的存放路径'''
def file_path(path,directory,filename):
    '''
    directory:目录名
    filename:文件名
    path：项目根目录
    '''
    file_path = os.path.join(path,directory,filename)
    return file_path

'''校验目录是否存在 不存在则创建目录'''
def check_list(path):
    bool = os.path.isdir(path)  # 校验目录是否存在
    if bool == False:
        os.makedirs(path)  # 不存在则创建

''' 时间戳--获取时间'''
def date(format):
    date = time.strftime(format, time.localtime())#format：展示格式，比如"%Y-%m-%d %H:%M:%S"
    return date

'''时间戳--获取昨天的日期'''
def yesterday():
    today = datetime.date.today()
    yesterday = today - datetime.timedelta(days=1)
    return str(yesterday)

'''读取yml文件--返回字典类型'''
def read_yml(filename):
    path = os.path.join(FILE_PATH, filename)
    conf_run = Yaml(path)  # 打开Yaml文件
    conf_val = conf_run.data[0]  # 获取Yaml文件中的第一个字典的数据
    return conf_val

'''js语言'''
def js(self, script):
    """script:js语句"""
    self.driver.execute_script(script)


#=========================selenium====================================================
'''初始化浏览器'''
def brower(brower):
    if brower == 'firefox' or brower == 'Firefox' or brower == 'f' or brower == 'F':
        driver = webdriver.Firefox()
    elif brower == 'Ie' or brower == 'ie' or brower == 'i' or brower == 'I':
        driver = webdriver.Ie()
    elif brower == 'Chrome' or brower == 'chrome' or brower == 'Ch' or brower == 'ch':
        driver = webdriver.Chrome(Driver_PATH + r'\chromedriver.exe')
    elif brower == 'PhantomJS' or brower == 'phantomjs' or brower == 'ph' or brower == 'phjs':
        driver = webdriver.PhantomJS()
    elif brower == 'Edge' or brower == 'edge' or brower == 'Ed' or brower == 'ed':
        driver = webdriver.Edge()
    elif brower == 'Opera' or brower == 'opera' or brower == 'op' or brower == 'OP':
        driver = webdriver.Opera()
    elif brower == 'Safari' or brower == 'safari' or brower == 'sa' or brower == 'saf':
        driver = webdriver.Safari()
    else:
        raise NameError('只能输入firefox,Ie,Chrome,PhantomJS,Edge,Opera,Safari')
    return driver

'''定位'''
def element(driver, method, selector):
    if method == 'id':
        element = driver.find_element_by_id(selector)
    elif method == "name":
        element = driver.find_element_by_name(selector)
    elif method == "class":
        element = driver.find_element_by_class_name(selector)
    elif method == "link_text":
        element = driver.find_element_by_link_text(selector)
    elif method == "xpath":
        element = driver.find_element_by_xpath(selector)
    elif method == "tag":
        element = driver.find_element_by_tag_name(selector)
    elif method == "css":
        element = driver.find_element_by_css_selector(selector)
    else:
        raise NameError("Please enter the  elements,'id','name','class','link_text','xpath','css','tag'.")
    return element


'''打开Url'''
def GetUrl(driver,url):
    driver.get(url)  # 打开url


'''浏览器最大化'''
def maxWindow(driver):
    driver.maximize_window()

'''隐性等待时间'''
def wait(driver,val):
    driver.implicitly_wait(val)

def count_lists(driver, method, selector):
    '''获取集合的长度'''
    list = element(driver, method, selector)
    lists = len(list)
    return lists

'''文本框--清空文本框'''
def clear(driver, method, selector):
    element(driver, method, selector).clear()  # 清空

'''文本框--输入数据'''
def input_data(driver, method, selector, val):
    element(driver, method, selector).send_keys(val)  # 输入值
'''按钮'''
def Click(driver, method, selector):
    element(driver, method, selector).click()

'''下拉菜单通过可见文本去选择'''
def option(driver,method, selector,val):
    select = Select(element(driver, method, selector))
    select.select_by_visible_text(val)  # 通过可见文本去选择

'''键盘模拟回车键'''
def key(driver,method, selector):
    element(driver, method, selector).send_keys(Keys.ENTER)

'''浏览器--新开页面'''
def ctrl_T(driver,testurl):
    js = "window.open('"+testurl+"')"
    driver.execute_script(js)

'''获取元素的属性值'''
def get_att(driver, method, selector,ment):
    #element:元素属性标签
    val = element(driver, method, selector).get_attribute(ment)
    return val

'''获取文本'''
def text_val(driver,method, selector):
    val = element(driver, method, selector).text
    return val

'''元素方法is_selected()返回是是布尔值，用来判断单选或者多选控件是否被选中，或者下拉选择菜单是否选择一个默认的option，都可以通过这个方法去判断'''
def is_selected(driver,method, selector):
    val = element(driver, method, selector).is_selected()
    return val

'''元素方法is_enabled()返回是是布尔值，用来判断是否置灰不可用'''
def is_enabled(driver,method, selector):
    val = element(driver, method, selector).is_enabled()
    return val

'''获取元素属性'''
def attribute(driver,method, selector,element_val):
    attribute = element(driver, method, selector).get_attribute(element_val)
    return attribute


'''确认元素是否存在，如果存在返回flag=true，否则返回false'''
def isElementExist(driver,method, selector):
    flag = True
    try:
        element(driver, method, selector)
        return flag
    except:
        flag = False
        return flag

'''元素是否可见'''
def displayed(str):
    bool = str.is_displayed()
    return bool

'''下拉滚动条,下拉到可见的元素'''
def scroll(driver,method, selector):
    ele = element(driver, method, selector)
    actions = ActionChains(driver)
    actions.move_to_element(ele).perform()

'''iframe处理'''
def iframe(driver,iframName):
    driver.switch_to.frame(iframName)

'''iframe切换回默认'''
def default_web(driver):
    driver.switch_to.default_content()

'''下拉滚动条找元素,获取文本,return:'''
def scroll_text(driver,method, selector, element, element1):
    start = element(driver, method, selector)  # 找到滚动条
    end = element(driver, element, element1) #元素定位
    bool = displayed(end)#元素是否可见
    if bool:
        val = text_val(driver, element, element1)#获取文本
        return val
    else:
        ActionChains(driver).drag_and_drop(start, end).perform()
        try:
            val = element(driver, element, element1).text
            return val
            # t = False
        except  Exception as e:
            print(e)

'''拖拽元素'''
def elementDragging(driver,ele,element):
    #定位起点
    start  = driver.find_element_by_css_selector(ele)
    # 定位元素要移动到的目标位置
    end = driver.find_element_by_css_selector(element)
    # 执行元素的拖放操作
    ActionChains(driver).drag_and_drop(start,end).perform()


'''鼠标悬停'''
def hover(driver, method, selector):
    mouse = element(driver, method, selector)
    ActionChains(driver).move_to_element(mouse).perform()

'''切换到新窗口'''
def Switch(driver):
    handles = driver.window_handles # 获取当前窗口句柄集合（列表类型）
    driver.switch_to.window(handles[-1])# 切换到当前最新打开的窗口

'''切换到原窗口'''
def Switching(driver):
    handles = driver.window_handles  # 获取当前窗口句柄集合（列表类型）
    driver.switch_to_window(handles[0])

'''关闭当前窗口'''
def close(driver):
    driver.close()

'''关闭浏览器'''
def quit(driver):
    driver.quit()


'''断言:判断value包含val'''
def as_contain(val,value):
    assert val in value

'''断言:判断value不包含val'''
def as_notContain(val, value):
    assert val not in value

'''断言:判断val为真'''
def as_true(val):
    assert val

'''断言:判断val不为真'''
def as_false(val):
    assert not val

'''断言:判断val等于value'''
def as_equal(val,value):
    assert val == value

'''断言:判断val不等于value'''
def as_notEqual(val, value):
    assert val != value

# '''多重校验'''
def assume(val, value):
    pytest.assume(val == value)

 #======================requset===========================

def lient(method,url,params = None,headers = None ,**kwargs):
    if method == 'get' or method =='GET':
        request = requests.get(url=url, params=params, headers=headers, **kwargs)
        return request
    elif method == 'post' or method =='POST':
        request = requests.post(url=url, params=params, headers=headers, **kwargs)
        return request

def text(request):

    '''返回响应的srt格式'''
    text_val = request.text
    return text_val

def code(request):
    '''返回状态码（成功为：200）'''
    code_val = request.status_code
    return code_val

def json_way(data):
    '''获取接口返回值的json()格式'''
    json_val = data.json()
    return json_val

def url(request):
    '''获取接口的url'''
    url_val = request.url
    return url_val

def encoding(request):
    '''获取接口的字符编码格式'''
    encoding_val = request.encoding
    return encoding_val

def header(request):
    '''获取接口的headers'''
    header_val = request.headers
    return header_val

def str_dict(data):
    '''str转换为dict；data为str'''
    dict = eval(data)
    return dict

def dict_str(data):
    '''dict转换为str；data为dict'''
    str = str(data)
    return str

if __name__ =='__main__':
    # print(date('%Y-%m-%d %H:%M:%S'))
    # print(random_number(1, 9))
    # value=2.3
    # print(type(value) ==float)
    headers = 'JSESSIONID=583737D8FF65BDE9AC69B3067548A7B1; Path=/javamall; HttpOnly'
    a = regEx(r"(.*);",headers)
    aa,bb =segmentation(a[0], ';')
    print(aa)
